﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KandaAlpha.Domain.Model.Proposed.ValueObjects;

namespace KandaAlpha.Domain.Model.Entities
{
    public class Classifier : EntityBase
    {

        private Classifier _parent;
        private List<Classifier> _children = new List<Classifier>();

        public string ClassifierRef { get; set; }

        public Classifier Parent 
        { 
            get {return _parent;}
            set
            {
                if (value == null)
                    throw new NotSupportedException("Parent cannot be null");

                if (_parent == null)
                {
                    _parent = value;
                    value.Children.Add(this);
                }
                else if (_parent.ID != value.ID)
                {
                    if (_parent.Children != null)
                    {
                        _parent.Children.RemoveAll(pc => pc.ID == this.ID);
                    }
                    _parent = value;
                    value.Children.Add(this);
                }
            }
        }

        public Classifier Family { get; set; }
        public List<Classifier> Children { get { return _children; } private set { _children = value; } }
        public string ClassifierName { get; set; }
        public string ClassifierDescription { get; set; }
        public int SortOrder { get; set; }
        public int Depth { get; set; }

        List<Classifier> GetAncestors(bool ignoreRoot)
        {
            return RecursiveGetAncestors(null, this.Parent, ignoreRoot);
        }

        private List<Classifier> RecursiveGetAncestors(List<Classifier> ancestors, Classifier classifier, bool ignoreRoot)
        {
            if (ancestors == null)
            {
                ancestors = new List<Classifier>();
            }
            if (classifier == null)
            {
                return ancestors;
            }
            if (!(ignoreRoot && this.Parent == null))
            {
                ancestors.Add(classifier);
            }
            return RecursiveGetAncestors(ancestors, classifier.Parent, ignoreRoot);
        }

    }
}
